import java.util.LinkedList;
import java.util.List;

/**
 * 46. 全排列
 * https://leetcode.cn/problems/permutations/description/
 */
class Solution3 {
    List<List<Integer>> ret;
    List<Integer> path;
    boolean[] check;

    public List<List<Integer>> permute(int[] nums) {
        int n = nums.length;
        ret = new LinkedList<>();
        path = new LinkedList<>();
        check = new boolean[n];

        dfs(nums);

        return ret;
    }

    public void dfs(int[] nums) {
        int n = nums.length;
        if(path.size() == n) {
            ret.add(new LinkedList<>(path));
            return;
        }

        for(int i = 0; i < n; i++) {
            if(!check[i]) {
                path.add(nums[i]);
                check[i] = true;
                dfs(nums);
                check[i] = false;
                path.remove(path.size() - 1);
            }
        }
    }
}